from datetime import datetime, timedelta
from typing import Optional

import croniter

from app.core.constants import TriggerType
from app.core.task.triggers.base import BaseTrigger
from app.utils.timezone import now


class CronTrigger(BaseTrigger):
    trigger_type = TriggerType.CRON

    def __init__(self, cron_expression: str):
        super().__init__(cron_expression=cron_expression)

    async def get_next_fire_time(self, previous_fire_time: Optional[datetime]) -> Optional[datetime]:
        base_time = previous_fire_time or now()
        cron = croniter.croniter(self.params["cron_expression"], base_time)
        return cron.get_next(datetime)
